<template>
  <div class="answer_container">
    <div class="left">
      <div class="squares-container">
        <div
          v-for="i in total"
          :key="i"
          class="square_item"
          :style="getStyle(i)"
          @click="changeIndex(i)"
        >
          {{ i }}
        </div>
      </div>
    </div>
    <div class="right">
      <div class="center_content" ref="centerContent">
        <span
          style="display: block; margin-top: 20px; margin-bottom: 40px"
          :key="item.id"
          >{{ index + 1 }}.{{ item.question }}</span
        >
        <el-radio-group
          class="option-group"
          v-model="selectedRatio"
          v-show="item.answer.length == 1"
        >
          <div class="option-item">
            <el-radio value="A" :label="item.item1" @click="radioHandler" />
          </div>
          <div class="option-item">
            <el-radio value="B" :label="item.item2" @click="radioHandler" />
          </div>
          <div class="option-item">
            <el-radio value="C" :label="item.item3" @click="radioHandler" />
          </div>
          <div v-if="item.item4" class="option-item">
            <el-radio value="D" :label="item.item4" @click="radioHandler" />
          </div>
        </el-radio-group>

        <el-checkbox-group
          class="option-group"
          v-model="selectedChecked"
          v-show="item.answer.length > 1"
        >
          <div class="option-item">
            <el-checkbox value="A" :label="item.item1" @click="checkHandler" />
          </div>
          <div class="option-item">
            <el-checkbox value="B" :label="item.item2" @click="checkHandler" />
          </div>
          <div class="option-item">
            <el-checkbox value="C" :label="item.item3" @click="checkHandler" />
          </div>
          <div v-if="item.item4" class="option-item">
            <el-checkbox value="D" :label="item.item4" @click="checkHandler" />
          </div>
        </el-checkbox-group>
        <div v-show="item.remark" style="margin-top: 20px">
          <span>答案解析： {{ item.remark }}</span>
        </div>
      </div>
      <div class="center_footer">
        <el-button type="warning" @click="showAnswer" icon="View"
          >答案</el-button
        >
        <div style="display: flex">
          <el-button type="primary" icon="ArrowLeft" @click="prev"
            >上一题</el-button
          >
          <el-button type="primary" icon="ArrowRight" @click="next"
            >下一题</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import zhiZhaoApi from "@/api/questionItem/questionItem";
// import feedBackApi from "@/api/feedBack";
import store from "@/store";
import { ref, onMounted, watch, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const show = ref(false);
const index = ref(0);
const total = ref(0);
const items = ref([]); //所有的题
const item = ref({
  subject: "",
  question: "",
  item1: "",
  item2: "",
  item3: "",
  item4: "",
  answer: "",
}); //单独的某一道题
const selectedRatio = ref(""); //选择单选题的答案
const selectedChecked = ref([]); //选择多选题的答案
const allAnswers = ref([]); //选择的所有题目的答案
const tapIndex = ref([]); //标记的题目的索引
const tappedfalg = ref(false); //表示某一题是否被标记过的索引
const feedback = ref(false);

watch(index, (newVal) => {
  selectedRatio.value = "";
  selectedChecked.value = [];
  item.value = items.value[newVal];
  if (tapIndex.value.includes(newVal)) {
    tappedfalg.value = true;
  } else {
    tappedfalg.value = false;
  }
  const res = allAnswers.value[newVal].filter((a) => a != "");
  if (items.value[newVal].answer.length > 1) {
    //多选题
    selectedChecked.value = res;
  } else {
    //单选题
    selectedRatio.value = res[0];
  }
});

// 在组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener("keydown", handleKeyboardNavigation);
});

const compare = (array, str) => {
  if (array.length == 1) {
    return array[0] == str;
  } else {
    let arr = "";
    for (let index = 0; index < array.length; index++) {
      const element = array[index];
      arr += element;
      if (index < array.length - 1) {
        arr += "+";
      }
    }
    return arr == str;
  }
};

const changeIndex = (item) => {
  index.value = item - 1;
};

const getStyle = (i) => {
  const data = {
    color: "#FFFFFF",
    "border-radius": "2px",
    border: "1px solid rgb(232, 221, 221)",
  };

  const item = i - 1;
  if (allAnswers.value[item] != undefined) {
    const answer = allAnswers.value[item].filter((a) => a != "");
    if (item == index.value) {
      data.backgroundColor = "#409eff !important";
      data.borderColor = "#409eff";
    } else if (tapIndex.value.includes(item)) {
      data.backgroundColor = "#e6a23c !important";
      data.borderColor = "#e6a23c";
    } else {
      if (compare(answer, items.value[item].answer)) {
        data.backgroundColor = "#67c23a !important";
        data.borderColor = "#67c23a";
      } else {
        data.backgroundColor = "#f56c6c !important";
        data.borderColor = "#f56c6c";
      }
    }
  }
  return data;
};

const setAllAnswers = (item) => {
  switch (item) {
    case "A":
      allAnswers.value[index.value][0] = item;
      break;
    case "B":
      allAnswers.value[index.value][1] = item;
      break;
    case "C":
      allAnswers.value[index.value][2] = item;
      break;
    case "D":
      allAnswers.value[index.value][3] = item;
      break;
    default:
      break;
  }
};

const radioHandler = () => {
  for (let i = 0; i < 4; i++) {
    allAnswers.value[index.value][i] = "";
  }
  setAllAnswers.value(selectedRatio.value);
};

const checkHandler = () => {
  for (let i = 0; i < 4; i++) {
    allAnswers.value[index.value][i] = "";
  }
  for (let i = 0; i < selectedChecked.value.length; i++) {
    const element = selectedChecked.value[i];
    setAllAnswers.value(element);
  }
};

// 方法定义
const tap = () => {
  if (!tappedfalg.value) {
    tapIndex.value.push(index.value);
    tappedfalg.value = true;
  } else {
    tapIndex.value = tapIndex.value.filter((e) => e !== index.value);
    tappedfalg.value = false;
  }
};

const next = () => {
  if (index.value === total.value - 1) {
    ElMessage.error("已经是最后一题了！");
    return;
  }
  index.value++;
};

const prev = () => {
  if (index.value === 0) {
    ElMessage.error("已经是第一题了！");
    return;
  }
  index.value--;
};

const showAnswer = () => {
  console.log(item.value.answer);

  if (item.value.answer.length === 1) {
    selectedRatio.value = item.value.answer;
  } else {
    selectedChecked.value.splice(
      0,
      selectedChecked.value.length,
      ...item.value.answer.split("+")
    );
  }
};

// const feedBack = async () => {
//   try {
//     const res = await feedBackApi.insert(item.value.id);
//     ElMessage.success(res.message);
//   } catch (error) {
//     console.error(error);
//   }
// };

const router = useRouter();

// 初始化逻辑
const init = async () => {
  const { questionItemId, account } = route.query;
  if (!questionItemId || !account) {
    router.push({ path: "/testResult/index" });
    return;
  }

  try {
    const res = await zhiZhaoApi.getItem(questionItemId);
    items.value = res.data.result;
    item.value = items.value[0];
    total.value = items.value.length;

    const response = await zhiZhaoApi.getMyAnswers(questionItemId, account);
    for (let i = 0; i < total.value; i++) {
      allAnswers.value.push([
        response.data[i][0],
        response.data[i][1],
        response.data[i][2],
        response.data[i][3],
      ]);
    }

    const ans = allAnswers.value[0].filter((a) => a !== "");
    if (ans.length === 1) {
      selectedRatio.value = ans[0];
    } else {
      selectedChecked.value.splice(0, selectedChecked.length, ...ans);
    }
  } catch (error) {
    console.error(error);
  }
};

// 权限判断
feedback.value = store.getters.roles.some((role) =>
  ["teacher", "admin"].includes(role)
);

/**
 * 处理键盘导航事件
 * @param {KeyboardEvent} event - 键盘事件
 */
const handleKeyboardNavigation = (event) => {
  // 如果用户正在输入框中输入，不处理键盘导航
  if (event.target.tagName === "INPUT" || event.target.tagName === "TEXTAREA") {
    return;
  }

  if (event.key === "ArrowLeft") {
    prev();
  } else if (event.key === "ArrowRight") {
    next();
  }
};

// 生命周期钩子
onMounted(() => {
  init();
  // 添加键盘事件监听
  window.addEventListener("keydown", handleKeyboardNavigation);
});
</script>
<style scoped>
.answer_container {
  display: flex;
  justify-content: space-between;
  display: flex;
  flex-direction: row;
}

.left {
  width: 300px;
  padding: 10px;
  height: 70vh;
  overflow-y: auto;
  overflow-x: auto;
  background-color: white;
  border: solid 1px rgb(226, 226, 266);
  border-radius: 3px;
}

.right {
  margin-left: 20px;
  width: calc(100% - 320px);
  height: 70vh;
  overflow-y: auto;
  background-color: white;
  border: solid 1px rgb(226, 226, 266);
  border-radius: 3px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.squares-container {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
  padding: 10px;
}

.square_item {
  background-color: rgb(245, 245, 245);
  border: 1px solid rgb(232, 221, 221);
  border-radius: 2px;
  width: 35px;
  height: 25px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.center_content {
  overflow-y: auto;
  margin-left: 20px;
}

.center_footer {
  margin-top: 5px;
  margin-left: 20px;
  margin-right: 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

/* 修改一些样式以适应 Element Plus */
.el-radio-group,
.el-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.el-radio,
.el-checkbox {
  margin-right: 0;
}

/* 添加新的样式 */
.option-group {
  width: 100%;
  padding: 0 20px;
}

.option-item {
  width: 100%;
  margin-top: 10px;
}

.option-item :deep(.el-radio),
.option-item :deep(.el-checkbox) {
  width: 100%;
  margin-right: 0;
  padding: 8px 0;
}

.option-item :deep(.el-radio__label),
.option-item :deep(.el-checkbox__label) {
  white-space: normal;
  word-break: break-word;
}
</style>
